package com.example.firstdemo.ui.screens.pages.problem.problemDetail

import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.offset
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import androidx.wear.compose.material.ExperimentalWearMaterialApi
import androidx.wear.compose.material.FractionalThreshold
import androidx.wear.compose.material.rememberSwipeableState
import androidx.wear.compose.material.swipeable


@OptIn(ExperimentalWearMaterialApi::class)
@Composable
fun SwipeBackLayout(
    navController: NavController,
    content: @Composable () -> Unit
) {
    val screenWidth = LocalConfiguration.current.screenWidthDp.dp
    val threshold = 80.dp
    val endOffset = with(LocalDensity.current) { screenWidth.toPx() }

    val swipeableState = rememberSwipeableState(initialValue = false)
    val anchors = mapOf(
        0f to false,
        endOffset to true
    )

    LaunchedEffect(swipeableState.currentValue) {
        if (swipeableState.currentValue) {
            navController.popBackStack()
        }
    }

    Box(
        modifier = Modifier
            .fillMaxSize()
            .swipeable(
                state = swipeableState,
                anchors = anchors,
                thresholds = { _, _ -> FractionalThreshold(0.3f) },
                orientation = Orientation.Horizontal,
                enabled = swipeableState.currentValue == false // 只有未滑出时可滑动
            )
            .offset { IntOffset(swipeableState.offset.value.toInt(), 0) }
    ) {
        content()
    }
}